package br.com.felix.dbm.ui.components;

import java.awt.Color;

import javax.swing.JTextField;

import br.com.felix.dbm.DatabaseObjectsFactory;
import br.com.felix.dbm.controller.ColumnController;
import br.com.felix.dbm.ui.Style;

/**
 * Text Field for column names. Display different background colors according to
 * column name validation. Uses DatabaseNameKeyAdapter.
 * */
public class ColumnJTextField extends JTextField {
	private static final long serialVersionUID = -3713320587521990999L;
	private ColumnController columnController;
	private Color normalColor;
	private Color wrongColor = new Color(255, 120, 120);



	public ColumnJTextField(ColumnController columnController) {
		this.setFont(Style.getTextFont());
		this.normalColor = getBackground();
		this.setColumns(15);
		this.columnController = columnController;
		this.addKeyListener(new DatabaseNameKeyAdapter() {
			@Override
			public void afterKeyReleased() {
				int caret = getCaretPosition();
				String columnName = getText();
				ColumnJTextField.this.columnController.setName(columnName);
				ColumnJTextField.this.columnController.updateView();
				boolean isAValidColumnName = DatabaseObjectsFactory.getDatabaseNamingRules().isValidColumnName(columnName);
				if (isAValidColumnName) {
					setBackground(normalColor);
				}
				else {
					setBackground(wrongColor);
				}
				setCaretPosition(caret);
			}
		});

	}
}